package com.h5tools.ant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.selectors.FilenameSelector;
import org.apache.tools.zip.ZipOutputStream;

public class MakeZip extends Task {

	//	private File dir;
	//	public void setSrc(File f)
	//	{
	//		this.dir = f;
	//	}
	private String h5Id;
	public void setH5Id(String h5Id)
	{
		this.h5Id = h5Id;
	}
	public MakeZip() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void execute() throws BuildException {
		// TODO Auto-generated method stub
		//System.out.println(this.h5Id);
		System.out.println(getProject().getBaseDir());
		File baseDir = getProject().getBaseDir();
		//make folder
		File desDir = new File(baseDir.getParentFile(),"bin");
		if(!desDir.exists())
		{
			desDir.mkdir();
		}
		File hisDir = new File(desDir,"his");
		if(!hisDir.exists())
		{
			hisDir.mkdir();
		}
		File tmpDir = new File(desDir,"tmp");
		if(!tmpDir.exists())
		{
			tmpDir.mkdir();
		}
		else
		{
			DeleteFile(tmpDir,false);
		}
		if(this.h5Id.equals("${h5id}"))
		{
			//deploy所有,打包所有并deploy
			for(File f : baseDir.listFiles())
			{
				if(f.isDirectory())
				{
					String name = f.getName();
					System.out.println(String.format("start make zip [%s]", name));

					File h5dir = new File(baseDir,name);

					if(!h5dir.isDirectory())
					{
						throw new BuildException(String.format("%s is not a dir! please check", h5dir.toString()));
					}
					else
					{
						File h5cfg = new File(h5dir,"h5cfg.txt");
						if(!h5cfg.exists() && !h5cfg.isFile())
						{
							throw new BuildException(String.format("lose h5cfg.txt in dir %s! please check", h5dir.toString()));
						}
						else
						{
							File desZipFile = new File(desDir,String.format("%s.zip", name));
							this.zip(name, desZipFile);
							//成功后copy到back
							SimpleDateFormat bkfmt = new SimpleDateFormat("yyyyMMddHHmmss");
							String zipBack = String.format("%s_%s.zip", name,bkfmt.format(new Date()));
							File backFile = new File(hisDir,zipBack);
							File tmpFile = new File(tmpDir,String.format("%s.zip", name));
							try {
								this.copyFileTo(desZipFile, backFile);
								this.copyFileTo(desZipFile, tmpFile);
								System.out.println("suc");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

					}
				}
			}
		}
		else
		{
			//只打包单个
			File h5dir = new File(baseDir,this.h5Id);
			System.out.println(String.format("start make zip [%s]", h5Id));
			if(!h5dir.isDirectory())
			{
				throw new BuildException(String.format("%s is not a dir! please check", h5dir.toString()));
			}
			else
			{
				//check h5cfg.txt
				File h5cfg = new File(h5dir,"h5cfg.txt");
				if(!h5cfg.exists() && !h5cfg.isFile())
				{
					throw new BuildException(String.format("lose h5cfg.txt in dir %s! please check", h5dir.toString()));
				}
				else
				{
					File desZipFile = new File(desDir,String.format("%s.zip", this.h5Id));
					this.zip(this.h5Id, desZipFile);
					//成功后copy到back
					SimpleDateFormat bkfmt = new SimpleDateFormat("yyyyMMddHHmmss");
					String zipBack = String.format("%s_%s.zip", this.h5Id,bkfmt.format(new Date()));
					File backFile = new File(hisDir,zipBack);
					File tmpFile = new File(tmpDir,String.format("%s.zip", this.h5Id));
					try {
						this.copyFileTo(desZipFile, backFile);
						this.copyFileTo(desZipFile, tmpFile);
						System.out.println("suc");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

	}
	private void unZip(String destDir,String sourceZip){  

		try {  
			Project prj1 = new Project();  

			Expand expand = new Expand();  

			expand.setProject(prj1);  

			expand.setSrc(new File(sourceZip));  

			expand.setOverwrite(true);//是否覆盖  

			File f = new File(destDir);  

			expand.setDest(f);  

			expand.execute();  
		} catch (Exception e) {  
			e.printStackTrace();  
		}  
	}  


	/** 
	 * 压缩 
	 *  
	 * @param sourceFile 
	 *            压缩的源文件 如: c:/upload 
	 * @param targetZip 
	 *            生成的目标文件 如：c:/upload.zip 
	 */  
	private void zip(String dirName,File targetZip){  

		Project prj = new Project();
		Zip zip = new Zip();  

		zip.setProject(prj);  

		zip.setDestFile(targetZip);//设置生成的目标zip文件File对象  

		FileSet fileSet = new FileSet();  

		fileSet.setProject(prj);  

		fileSet.setDir(getProject().getBaseDir());//设置将要进行压缩的源文件File对象 

		//fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹,只压缩目录中的所有java文件  

		//fileSet.setExcludes("**/*.java"); //排除哪些文件或文件夹,压缩所有的文件，排除java文件  
		FilenameSelector a = new FilenameSelector();  
		a.setName(dirName+"/**/*");
		fileSet.add(a);
		zip.addFileset(fileSet);  
		//zip.addFileset(fileSet1); 
		zip.execute();

	}
	private boolean copyFileTo(File srcFile, File destFile) throws IOException {  
		if (srcFile.isDirectory() || destFile.isDirectory())  
			return false;// 判断是否是文件  
		FileInputStream fis = new FileInputStream(srcFile);  
		FileOutputStream fos = new FileOutputStream(destFile);  
		int readLen = 0;  
		byte[] buf = new byte[1024];  
		while ((readLen = fis.read(buf)) != -1) {  
			fos.write(buf, 0, readLen);  
		}  
		fos.flush();  
		fos.close();  
		fis.close();  
		return true;  
	}
	
	private void DeleteFile(File file,boolean delself) { 
		if (file.exists() == false) { 
			return; 
		} else { 
			if (file.isFile()) { 
				file.delete(); 
				return; 
			} 
			if (file.isDirectory()) { 
				File[] childFile = file.listFiles(); 
				if (childFile == null || childFile.length == 0) {
					if(delself)
					{
						file.delete(); 
					}
					return; 
				} 
				for (File f : childFile) { 
					DeleteFile(f,true); 
				} 
				if(delself)
				{
					file.delete(); 
				}
				//file.delete(); 
			} 
		}
	}

}
